<template>
    <tooltip 
        :open-tooltip="openTooltip" 
        :auto-tooltip="autoTooltip"
        :wapStyle="{ display: 'flex', width: '100%' }"
    >
        <template #title>{{ tipTitle }}</template>
        <Select
            ref="selectRef"
            style="width: 100%"
            v-bind="$attrs"
            :popupClassName="`edit-table-select`"
            :dropdownMatchSelectWidth="false"
            :class="{readonly: readonly}"
            :value="value"
            @update:value="v => value = v"
            @mouseenter="openTooltipHandel"
            @dropdownVisibleChange="dropdownVisibleChange"
            @contextmenu="selectRef.blur()"
        >
            <template #dropdownRender="{ menuNode: menu }">
                <v-nodes :vnodes="menu" />
                <div v-if="clearOption && value !== undefined" class="ant-select-item ant-select-item-option cancel" 
                    @mousedown="e => e.preventDefault()"
                    @click="value = undefined"
                >
                    <div class="ant-select-item-option-content">{{ clearOption?.label ?? "" }}</div>
                </div>
            </template>
            <template #option="scope">
                <div 
                    class="ant-select-item ant-select-item-option"
                    :class="{
                        'ant-select-item-option-selected': scope.value === value,
                        'ant-select-item-option-disabled': scope.disabled,
                    }"
                    :title="scope.label"
                    :key="scope.key"
                >
                    <div v-if="scope.disabled" class="ant-select-item-option-content">{{ scope.label }}</div>
                    <div v-else class="ant-select-item-option-content" @mousedown="value = scope.value">{{ scope.label }}</div>
                </div>
            </template>
            <template v-for="(slot, k) in $slots" :key="k" v-slot:[k]="slotProps">
                <slot :name="k" v-bind="slotProps ?? {}" ></slot>
            </template>
        </Select>
    </Tooltip>
</template>

<script lang="ts" setup>
import { useAttrs, ref, inject } from "vue"
import { Select } from "ant-design-vue"
import tooltip from "./tooltip.vue"
import { PROVIDE_READONLY } from "./../plugins/core/type"

const props = defineProps({
    isEditer: {
        type: Boolean,
        default: false,
    },
    openTooltip: {
        type: Boolean,
        default: false
    },
    clearOption: {
        type: [Object, Boolean],
        default: () => ({
            position: 'last', //'first' | 'last',
            label: '取消选择'
        }),
    },
    autoTooltip: {
        type: Boolean,
        default: true
    },
})

const VNodes = (_, { attrs }) => attrs.vnodes;
const value = defineModel('value')
const readonly = inject(PROVIDE_READONLY)

const tipTitle = ref<string>()
const attrs = useAttrs()

const openTooltipHandel = () => {
    const open = props.openTooltip && value.value !== undefined
    if(open){
        try{
            const val = value.value;
            if(val !== undefined){
                const { fieldNames } = attrs;
                const { label, value } = (fieldNames ?? attrs['field-names'] ?? { label: 'label', value: 'value' }) as {label: string, value: string};
                // console.info(label, value)
                if (Array.isArray(val)) {
                    tipTitle.value = attrs.options?.filter?.(op => val.includes(op[value]))?.map(v => v[label]).join(" , ")
                } else {
                    tipTitle.value = attrs.options?.find?.(op => op[value] === val)[label]
                }
            } else {
                tipTitle.value = undefined
            }
        }catch(e){
            tipTitle.value = undefined
        }
    }
}

const selectRef = ref();
let scrollWap: HTMLElement;
const scrollHandel = () => {
    Array.from(document.querySelectorAll('.edit-table-select') ?? [])?.forEach?.((el: HTMLElement) => {
        el.style.display = "none"
    })
    selectRef.value?.blur();
    scrollWap?.removeEventListener('scroll', scrollHandel)
}
const dropdownVisibleChange = (open: boolean) => {
    if (open) {
        if (!scrollWap) {
            let node = selectRef.value.$el;
            while(node.tagName !== 'TABLE') node = node.parentElement;
            scrollWap = node.parentElement.parentElement
        }
        scrollWap?.addEventListener('scroll', scrollHandel)
    } else {
        scrollWap?.removeEventListener('scroll', scrollHandel)
    }
}
</script>

<style scoped lang="less">
.readonly {
    pointer-events: none;
    :deep(.ant-select-arrow){
        display: none;
    }
}

:deep(.ant-select-selection-item){
    line-height: 21px !important;
}
</style>
<style lang="less">
.edit-table-select{
    padding: 0 !important;
    border-radius: 0 !important;
    .ant-select-item-option{
        font-size: 12px !important;
        line-height: 1.59999;
        padding: 2px 4px !important;
        min-height: unset !important;
        border-radius: 0 !important;
        background-color: transparent !important;
        &:not(.ant-select-item-option-selected):not(.ant-select-item-option-disabled):not(.cancel):hover{
            background: #e2f0ff !important;
        }
        &:not(.ant-select-item-option-disabled){
            cursor: pointer;
        }
        &.cancel {
            background-color: #f1f1f1 !important;
            color: rgba(0, 0, 0, 0.45) !important;
        }
    }
    .ant-select-item-option-active{
        background: transparent !important;
    }
    .ant-select-item-option-selected{
      background-color: #007fff !important;
      color: #fff !important;
    }
    .ant-select-item-option-disabled{
        cursor: not-allowed;
        color: rgba(0, 0, 0, 0.45) !important;
    }
}
</style>